// 选择资源
async function selectResourceByKey(workSpaceKey) {
    if (window.myData.unusedWorker <= 0) {
        return;
    }

    const mapping = resourceMappings[workSpaceKey];
    if (!mapping) {
        console.error(`No mapping found for workspace: ${workSpaceKey}`);
        return;
    }

    const isAccumulation = mapping.increaseStep > 0;
    let resourceAmount = isAccumulation ? window.boardData[workSpaceKey] : mapping.resourceAmount;

    if (isAccumulation && resourceAmount <= 0) {
        return;
    }

    if (!confirm('确定选择"' + mapping.workSpaceName + '"？')) {
        return;
    }

    const isTurnAction = turnCardsIdList.includes(workSpaceKey);
    if (isTurnAction) {
        await dispatchEvent(EVENT_USE_TURN_ACTION_BEFORE, { workSpaceKey });
    }

    window.myData[mapping.resourceType] += resourceAmount;
    window.myData.unusedWorker -= 1;
    
    if (isAccumulation) {
        window.boardData[workSpaceKey] = 0;
        updateAccumulationResource(workSpaceKey);

        dispatchEventDelay(EVENT_USE_RESOURCE_ACCUMULATION, { resourceType : mapping.resourceType , amountBeforeUse: resourceAmount, workSpaceKey : workSpaceKey});
    } else {
        dispatchEventDelay(EVENT_USE_RESOURCE, { workSpaceKey : workSpaceKey});
    }

    // 此处已经支持了非积累格可以获取动物
    if (mapping.isAnimal) {
        let stop = false;
        for (let i = window.myData.farmCells.length - 1; i >= 0; i--) {
            const colunm = window.myData.farmCells[i];
            for (let j = colunm.length - 1; j >= 0; j--) {
                const cell = colunm[j];
                if (cell.building == null || cell.building == "stable") {
                    if (cell.pig + cell.sheep + cell.cattle - cell[mapping.resourceType] == 0) { // 没有其他的动物
                        cell[mapping.resourceType] += resourceAmount;
                        stop = true;
                        break;
                    }
                }
            }
            if (stop) {
                break;
            }
        }
        updateFarm();
    }

    updateResourceBar();

    appendWorkerToTitle(`${mapping.id}`);
}

//----- 所有资源行动格的数据
// increaseStep: 0 则表示非积累资源格，并且有额外属性 resourceAmount 表示一次性获得的资源数量
const resourceMappings = {
    forest: { id: 'forest', resourceType: 'wood', workSpaceName: '森林', isAnimal: false , increaseStep: 3},
    'clay-pit': { id: 'clay-pit', resourceType: 'clay', workSpaceName: '黏土坑', isAnimal: false , increaseStep: 1},
    'reed-bank': { id: 'reed-bank', resourceType: 'reed', workSpaceName: '芦苇池', isAnimal: false , increaseStep: 1},
    fishing: { id: 'fishing', resourceType: 'food', workSpaceName: '钓鱼', isAnimal: false , increaseStep: 1},
    'sheep-market': { id: 'sheep-market', resourceType: 'sheep', workSpaceName: '羊市', isAnimal: true , increaseStep: 1},
    'west-stone-quarry': { id: 'west-stone-quarry', resourceType: 'stone', workSpaceName: '西采石场', isAnimal: false , increaseStep: 1},
    'pig-market': { id: 'pig-market', resourceType: 'pig', workSpaceName: '猪市', isAnimal: true , increaseStep: 1},
    'east-stone-quarry': { id: 'east-stone-quarry', resourceType: 'stone', workSpaceName: '东采石场', isAnimal: false , increaseStep: 1},
    'vegetable-seed': { id: 'vegetable-seed', resourceType: 'vegetable', workSpaceName: '蔬菜种子', isAnimal: false , increaseStep: 0, resourceAmount: 1},
    'grain-seed': { id: 'grain-seed', resourceType: 'grain', workSpaceName: '谷物种子', isAnimal: false , increaseStep: 0, resourceAmount: 1},
    'day-laborer': { id: 'day-laborer', resourceType: 'food', workSpaceName: '临时工', isAnimal: false , increaseStep: 0, resourceAmount: 2},
    'cattle-market': { id: 'cattle-market', resourceType: 'cattle', workSpaceName: '牛市', isAnimal: true, increaseStep: 1 },
};

function increaseAccumulationResource(workSpace, amount) {
    if (window.boardData[workSpace] === undefined) {
        return;
    }
    window.boardData[workSpace] += amount;
    updateAccumulationResource(workSpace);
}

function updateAccumulationResource(workSpace) {
    const resourceMapping = resourceMappings[workSpace];
    if (!resourceMapping) {
        console.error(`No mapping found for workspace: ${workSpace}`);
        return;
    }

    const { id , resourceType } = resourceMapping;
    const p = $(`#${id} p`);
    p.text(`+${TypeName[resourceType]}>>>${window.boardData[workSpace]}`);
}

// 更新所有积累格资源显示（并不改变当前的值）
function updateAllAccumulationResource() {
    for (let key in resourceMappings) {
        if (resourceMappings.hasOwnProperty(key)) {
            let resource = resourceMappings[key];
            if (resource.increaseStep > 0) {
                updateAccumulationResource(key);
            }
        }
    }
}

//----- 所有积累格增加资源
function resourceIncrease() {
    for (let key in resourceMappings) {
        if (resourceMappings.hasOwnProperty(key)) {
            let resource = resourceMappings[key];
            if (resource.increaseStep > 0) {
                let amountBeforeIncrease = window.boardData[key]; // 记录增加之前的资源数
                increaseAccumulationResource(key, resource.increaseStep);
                dispatchEvent(EVENT_RESOURCE_GROWTH, { workSpace: key, workSpaceData: resource, amountBeforeIncrease: amountBeforeIncrease });
            }
        }
    }
}